<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
      <el-form-item label="ID" prop="id">
        <el-input v-model="queryParams.id" placeholder="ID"></el-input>
      </el-form-item>
      <el-form-item label="所属模块" prop="module">
        <el-input v-model="queryParams.module" placeholder="所属模块"></el-input>
      </el-form-item>
      <el-form-item label="原文件名" prop="originalFileName">
        <el-input v-model="queryParams.originalFileName" placeholder="原文件名"></el-input>
      </el-form-item>
      <el-form-item label="fastdfs路径" prop="path">
        <el-input v-model="queryParams.path" placeholder="fastdfs路径"></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="图片状态"
          clearable
          size="small"
          style="width: 240px"
        >
          <el-option
            v-for="(data,index) in statusOptions"
            :key="index"
            :label="data.label"
            :value="data.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-has-permi="['user:image:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleEdit"
          v-has-permi="['user:image:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-has-permi="['user:image:delete']"
        >删除
        </el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table
      v-loading="loading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
      key="image"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column align="center" label="ID">
        <template slot-scope="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>
      <el-table-column label="所属模块" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.module }}</span>
        </template>
      </el-table-column>
      <el-table-column label="原文件名" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.originalFileName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="fastdfs路径" align="center">
        <template slot-scope="scope">
          <el-image :src="'http://www.feige.run/' + scope.row.path" :title="scope.row.path">
            <div slot="placeholder" class="image-slot">
              加载中<span class="dot">...</span>
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0"
                     @change="handleStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="created_at" label="创建时间">
        <template slot-scope="scope">
          <i class="el-icon-time"/>
          <span>{{ scope.row.gmtCreate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleEdit(scope.row)"
            v-has-permi="['user:image:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-has-permi="['user:image:delete']"
          >删除
          </el-button>
          <el-button
            type="text"
            icon="el-icon-download"
            size="mini"
            @click="handleDownload(scope.row)"
            v-has-permi="['user:image:download']"
          >下载
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 用户上传对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-form ref="form" :model="upload" :rules="rules" label-width="80px">
        <el-row>
          <el-col>
            <el-form-item label="所属模块" prop="module">
              <el-input v-model="upload.module" placeholder="请输入所属模块" maxlength="50"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-upload ref="upload" :limit="9" accept=".png, .jpg, .jpeg, .gif" :headers="upload.headers"
                 :action="upload.url + '?module=' + upload.module" :disabled="upload.isUploading"
                 :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" multiple
                 drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将图片拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许上传"png","gif","jpg","jpeg"格式图片！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import Image from "@/api/image/image";
  import {getToken} from "@/utils/auth";

  export default {
    data() {
      return {
        list: [],
        // 遮罩层
        loading: true,
        // 选中数组的ID
        ids: [],
        //选中数组的路径
        paths: [],
        //选中数组的所属模块
        module: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 日期范围
        dateRange: [],
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          id: undefined,
          module: undefined,
          originalFileName: undefined,
          path: undefined,
          status: undefined
        },
        // 用户导入参数
        upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "",
          //所属模块
          module: "",
          // 是否禁用上传
          isUploading: false,
          // 设置上传的请求头部
          headers: {token: getToken()},
          // 上传的地址
          url: "http://localhost:8080/fdfs/upload",
        },
        // 状态数据字典
        statusOptions: [
          {
            value: 1,
            label: '正常'
          },
          {
            value: 0,
            label: '禁用'
          }
        ],
        rules: {
          module: [
            {required: true, message: "所属模块不能为空", trigger: "blur"}
          ]
        }
      }
    },
    created() {
      this.getList();
    },
    methods: {
      getList() {
        this.loading = true;
        Image.getPageList(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.list = response.data;
          this.total = response.total;
          this.loading = false
        })
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.dateRange = [];
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id);
        this.paths = selection.map(item => item.path);
        this.module = selection.map(item => item.module);
        this.single = selection.length !== 1;
        this.multiple = !selection.length
      },
      // 图片信息状态修改
      handleStatusChange(row) {
        let text = row.status === 1 ? "启用" : "禁用";
        this.$confirm(
          '确认要"' + text + '""路径为' + row.path + '"的图片吗?',
          "警告",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(function () {
            return Image.updateStatus(row.id, row.status);
          })
          .then(() => {
            this.msgSuccess(text + "成功");
          })
          .catch(function () {
            row.status = row.status === 0 ? 1 : 0;
          });
      },
      handleEdit(row) {
        const id = row.id || this.ids[0];
        const module = row.module || this.module;
        this.$prompt('确认修改"' + module + '"吗？', "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
        })
          .then(({value}) => {
            if (value === null || value === '') {
              this.msgSuccess("所属模块不能为空！");
              return;
            }
            let image = {
              id: id,
              module: value
            };
            Image.updateById(image).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("修改成功，所属模块为：" + value);
                this.getList();
              }
            });
          })
          .catch((err) => {
            console.log(err);
          });
      },
      handleAdd() {
        this.upload.open = true;
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$confirm('是否确认删除编号为"' + ids + '"的图片信息吗?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          if (this.ids.length === 0) {
            return Image.removeByPath(row.path)
          } else {
            return Image.removeRows(this.paths);
          }
        })
          .then(() => {
            this.getList();
            this.msgSuccess("删除成功");
          })
          .catch(err => {
            console.log(err);
          });
      },
      /** 下载图片 */
      handleDownload(row) {
        window.location.href = `http://localhost:8080/fdfs/download?path=${row.path}`;
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.upload.open = false;
        this.upload.module = '';
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.$alert(response.msg, "导入结果", {dangerouslyUseHTMLString: true});
        this.getList();
      },
      // 提交上传文件
      submitFileForm() {
        this.$refs["form"].validate((valid) => {
          if (valid) {
            this.$refs.upload.submit();
          }
        })
      },
    }
  }
</script>

<style lang="scss" scoped>

</style>
